/**
 * weapp-js
 * https://code.aliyun.com/jionglee/weapp_base.git
 * Copyright@ 2020 Motigo, Inc.
 * 
 */
/*
ad_info数据结构:
{
    type: '',
    title: '',
    thumb: '',
    param: ''
    adtag: ''
}
 */
import ui from './ui.js';

export default {
    _handlers: null,
    handle(ad_info) {
        this._init();
        ad_info = ad_info || {};
        const ad_type = ad_info.type;
        const handler = this._handlers[ad_type];

        if (handler) {
            handler(ad_info.param);
        } else {
            console.error(`invalid ad type: ${ad_type}, info: ${ad_info}`);
        }
    },
    _init() {
        if(this._handlers) {
            return;
        }

        this._handlers = {
            'page': this.__page_handler.bind(this),
            'web': this.__web_handler.bind(this),
            'popup-image': this.__popup_image_handler.bind(this)
        }
    },
    __page_handler(url) {
        const page_url = '../../' + url;
        wx.navigateTo({
            url: page_url,
            fail: (res) => {                
                if(res.errMsg.indexOf('a tabbar page') > 0) {
                    wx.switchTab({
                        url: page_url,
                        fail: (res) => {
                            console.error('switch tab fail:', res)
                        }
                    })
                } else {
                    console.error('navigate to fail:', res);
                }
            }
        })
    },
    __web_handler(url) {
        this.__page_handler('pages/web/web?q=' + encodeURIComponent(url));
    },
    
    /* 图片弹窗
       data:
       {
           src: '',     // 图片链接
           desc: '',    // 图片描述，可空，支持富文本，如：长按保存<span style="color: red;">二维码</span>，扫描添加微信，咨询每人一张，先到先得
           width: 750,  // 图片显示宽度，最大750
           height: 500, // 图片显示高度
       }
     */
    __popup_image_handler(data) {
        ui.previewImage({
            urls: [{
                src: data.src,
                desc: data.desc
            }],
            width: data.width,
            height: data.height
        })
    }
}